package com.service.user;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

public class UserDAOHibernate implements UserDAO {

	private Session session;
	
	public void setSession(Session session) {
		this.session = session;
	}

	public void salvar(User user) {
		this.session.save(user);

	}

	public void atualizar(User user) {
		if(user.getRole() == null || user.getRole().size() == 0){
			User usuarioPermissao = this.carregar(user.getUserID());
			user.setRole(usuarioPermissao.getRole());
			this.session.evict(usuarioPermissao);
		}
		this.session.update(user);
	}
	
	public void excluir(User user) {
		this.session.delete(user);

	}

	public User carregar(Integer userID) {
		return (User) this.session.get(User.class, userID);
	}

	public User buscaPorLogin(String login) {
		String hql = "select u from User u where u.login = :login";
		Query consulta = this.session.createQuery(hql);
		consulta.setString("login", login);
		return (User) consulta.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<User> listar() {
		return this.session.createCriteria(User.class).list();
	}

}
